package com.budwk.app.sqfw.services.communityservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.bo.SqfwShopInfoDownloadBO;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.CommonForAdminConstants;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.dto.ShopInfoRecordMainKeyDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.*;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.enums.jinYang.JinYangExcelEnum;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.models.Sys_dict;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.SqfwInfoDataEasyExcelListener;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.enums.LogType;
import com.budwk.starter.log.model.Sys_log;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.R;
import org.nutz.mvc.upload.TempFile;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @program: dfxy-community
 * @description: 商铺数据管理（后台管理系统）
 * @author: LJT
 * @create: 2024-07-02 10:45
 **/
@IocBean
@Slf4j
public class SqfwShopInfoForAdminService {
    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private SysLogService sysLogService;

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Inject
    private BaseTemplateExcelGenerator baseTemplateExcelGenerator;

    @Inject
    private SysDictService sysDictService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SysUserService sysUserService;

    public Pagination page(SqfwShopInfoVO bean) {
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        Pagination pagination = shopsBaseInfoService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        List<SqfwShopsBaseInfo> sqfwShopsBaseInfos = pagination.getList(SqfwShopsBaseInfo.class);
        if (ObjectUtil.isNotEmpty(sqfwShopsBaseInfos)) {
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictInfoMaps(Arrays.asList(DictConstants.MAIN_BUSINESS_SCOPE));
            List<SqfwShopInfoVO> sqfwShopInfoVOS = new ArrayList<SqfwShopInfoVO>();
            sqfwShopsBaseInfos.forEach(source -> {
                SqfwShopInfoVO target = new SqfwShopInfoVO();
                BeanUtil.copyProperties(source, target);
                target.setOperatorTelephone(DesensitizedUtil.mobilePhone(source.getOperatorTelephone()));
                target.setSocialCreditCode(CharSequenceUtil.hide(source.getSocialCreditCode(), 0, 3));
                // 主营业务转换
                target.setMainBusinessScopeName(StringUtils.isEmpty(dictCodesMap.get(target.getMainBusinessScope())) ?
                        target.getMainBusinessScope() : dictCodesMap.get(target.getMainBusinessScope()));
                // 业务类型转换
                String serviceType = target.getServiceType();
                if (StringUtils.isNotEmpty(serviceType)) {
                    List<String> serviceTypes = Arrays.asList(serviceType.split(","));
                    StringBuffer sb = new StringBuffer();
                    serviceTypes.forEach(service -> {
                        sb.append(SupportBusinessTypeEnum.getNameByCode(service)).append(",");
                    });
                    serviceType = sb.substring(0, sb.length() - 1);
                }
                target.setServiceTypeName(StringUtils.isNotEmpty(serviceType) ? serviceType : target.getServiceType());
                sqfwShopInfoVOS.add(target);
            });
            pagination.setList(sqfwShopInfoVOS);
        }
        log.info("SqfwCustomForAdminCommonServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    /**
     * 详情查询
     *
     * @param id
     * @return
     */
    public SqfwShopsBaseInfo detail(String flag, String id) {
        Cnd cnd = Cnd.NEW();
        cnd.and(SqfwShopsBaseInfo::getId, "=", id);
        SqfwShopsBaseInfo sqfwShopsBaseInfo = shopsBaseInfoService.fetch(cnd);
        if (sqfwShopsBaseInfo == null) {
            return new SqfwShopsBaseInfo();
        }
        SqfwShopsBaseInfo sqfwShopsBaseInfoRes = new SqfwShopsBaseInfo();
        if ("1".equals(flag)) {
            sqfwShopsBaseInfoRes.setOperatorTelephone(DesensitizedUtil.mobilePhone(sqfwShopsBaseInfo.getOperatorTelephone()));
        } else {
            sqfwShopsBaseInfoRes.setOperatorTelephone(sqfwShopsBaseInfo.getOperatorTelephone());
        }
        return sqfwShopsBaseInfoRes;
    }

    @Aop(TransAop.READ_COMMITTED)
    public int update(SqfwShopInfoVO SqfwShopInfoVO) {
        return 0;
    }

    private Criteria buildQueryCond(SqfwShopInfoVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        // 组装查询条件
        cri.getOrderBy().desc(SqfwShopsBaseInfo::getUpdateDate);
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonForAdminConstants.ZHISHU.equals(bean.getProvince())) {
            criSql.andLike(SqfwShopsBaseInfo::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonForAdminConstants.ZHISHU.equals(bean.getCity())) {
            criSql.andLike(SqfwShopsBaseInfo::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonForAdminConstants.ZHISHU.equals(bean.getDistrict())) {
            criSql.andLike(SqfwShopsBaseInfo::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonForAdminConstants.ZHISHU.equals(bean.getCounty())) {
            criSql.andLike(SqfwShopsBaseInfo::getCounty, bean.getCounty());
        }
        // 社区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonForAdminConstants.ZHISHU.equals(bean.getCounty())) {
            criSql.andLike(SqfwShopsBaseInfo::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup placeName = Cnd.exps(SqfwShopsBaseInfo::getPlaceName, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup createName = Cnd.exps(SqfwShopsBaseInfo::getCreateId, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup county = Cnd.exps(SqfwShopsBaseInfo::getCounty, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup district = Cnd.exps(SqfwShopsBaseInfo::getDistrict, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup community = Cnd.exps(SqfwShopsBaseInfo::getCommunity, "like", "%" + bean.getQueryAll() + "%");
            criSql.and(placeName.or(createName).or(county).or(district).or(community));
        }
        // 店铺名称
        if (StringUtils.isNotBlank(bean.getPlaceName())) {
            criSql.andLike(SqfwShopsBaseInfo::getPlaceName, bean.getPlaceName());
        }
        // 社会信用代码
        if (StringUtils.isNotBlank(bean.getSocialCreditCode())) {
            criSql.andLike(SqfwShopsBaseInfo::getSocialCreditCode, bean.getSocialCreditCode());
        }
        // 管理人员
        if (StringUtils.isNotBlank(bean.getOperator())) {
            criSql.andLike(SqfwShopsBaseInfo::getOperator, bean.getOperator());
        }
        // 联系电话
        if (StringUtils.isNotBlank(bean.getOperatorTelephone())) {
            criSql.andLike(SqfwShopsBaseInfo::getOperatorTelephone, bean.getOperatorTelephone());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween("update_date",
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 主营业务
        if (StringUtils.isNotBlank(bean.getMainBusinessScope())) {
            criSql.andLike(SqfwShopsBaseInfo::getMainBusinessScope, bean.getMainBusinessScope());
        }
        // 类型
        if (StringUtils.isNotBlank(bean.getType())) {
            criSql.andLike(SqfwShopsBaseInfo::getType, bean.getType());
        }
        // 商铺状态
        if (StringUtils.isNotBlank(bean.getShopStatus())) {
            if ("0".equals(bean.getShopStatus())) {
                criSql.andEquals(SqfwShopsBaseInfo::getShopStatus, "3");
            } else {
                criSql.andNotEquals(SqfwShopsBaseInfo::getShopStatus, "3");
            }
        }
        return cri;
    }

    /**
     * 商铺信息导入
     *
     * @param file
     * @param bean
     * @return
     */
    public String uploadShopInfo(TempFile file, SqfwShopInfoVO bean) {
        if (file.getSize() <= 0) {
            return "文件不能为空！";
        }
        if (!file.getFile().getName().endsWith(".xlsx")) {
            return "文件格式不正确！";
        }
        String resStr = "";
        List<SqfwShopsBaseInfo> shopUpdateLog = new ArrayList<SqfwShopsBaseInfo>();
        List<SqfwShopsBaseInfo> shopInsertLog = new ArrayList<SqfwShopsBaseInfo>();
        // 解析导入文件
        long startTime = System.currentTimeMillis();
        SqfwInfoDataEasyExcelListener<SqfwShopInfoDownloadBO> listener = new SqfwInfoDataEasyExcelListener<>();
        try {
            EasyExcel.read(file.getInputStream(), SqfwShopInfoDownloadBO.class, listener).headRowNumber(3).sheet(0).doReadSync();
            List<SqfwShopInfoDownloadBO> data = listener.getData();
            String userId = SecurityUtil.getUserId();
            int updateNum = 0;
            for (SqfwShopInfoDownloadBO summaryBO : data) {
                SqfwShopsBaseInfo sqfwShopsBaseInfo = new SqfwShopsBaseInfo();
                BeanUtil.copyProperties(summaryBO, sqfwShopsBaseInfo);
                sqfwShopsBaseInfo.setShopStatus("1");
                sqfwShopsBaseInfo.setInspectionSituation("1");
                sqfwShopsBaseInfo.setCreateDate(LocalDateTimeUtil.now());
                sqfwShopsBaseInfo.setCreateId(userId);
                sqfwShopsBaseInfo.setProvince(bean.getProvince());
                sqfwShopsBaseInfo.setCity(bean.getCity());
                sqfwShopsBaseInfo.setDistrict(bean.getDistrict());
                sqfwShopsBaseInfo.setCounty(StringUtils.isEmpty(bean.getCounty()) ? CommonForAdminConstants.ZHISHU : bean.getCounty());
                sqfwShopsBaseInfo.setCommunity(StringUtils.isEmpty(bean.getCommunity()) ? CommonForAdminConstants.ZHISHU : bean.getCommunity());
                sqfwShopsBaseInfo.setDeleted(false);
                sqfwShopsBaseInfo.setDetailAddress(sqfwShopsBaseInfo.getAddress());
                sqfwShopsBaseInfo.setServiceType(StringUtils.isNotEmpty(sqfwShopsBaseInfo.getServiceType()) ?
                        sqfwShopsBaseInfo.getServiceType().replaceAll("\\|", ",") : "");
                // 检查更更新或者新增
                Cnd cnd = Cnd.NEW();
                cnd.and(SqfwShopsBaseInfo::getProvince, "=", sqfwShopsBaseInfo.getProvince())
                        .and(SqfwShopsBaseInfo::getCity, "=", sqfwShopsBaseInfo.getCity())
                        .and(SqfwShopsBaseInfo::getDistrict, "=", sqfwShopsBaseInfo.getDistrict())
                        .and(SqfwShopsBaseInfo::getCounty, "=", sqfwShopsBaseInfo.getCounty())
                        .and(SqfwShopsBaseInfo::getCommunity, "=", sqfwShopsBaseInfo.getCommunity())
                        .and(SqfwShopsBaseInfo::getAddress, "=", sqfwShopsBaseInfo.getAddress())
                        .and(SqfwShopsBaseInfo::getPlaceName, "=", sqfwShopsBaseInfo.getPlaceName());
                SqfwShopsBaseInfo sqfwShopsBaseInfo1 = shopsBaseInfoService.fetch(cnd);
                if (null != sqfwShopsBaseInfo1) {
                    shopUpdateLog.add(sqfwShopsBaseInfo1);// 原数据记录到日志
                    sqfwShopsBaseInfo.setId(sqfwShopsBaseInfo1.getId());
                    BeanUtil.copyProperties(sqfwShopsBaseInfo, sqfwShopsBaseInfo1);
                    sqfwShopsBaseInfo1.setUpdateDate(LocalDateTimeUtil.now());
                    sqfwShopsBaseInfo.setUpdateId(userId);
                    shopsBaseInfoService.updateIgnoreNull(sqfwShopsBaseInfo);
                    updateNum++;
                } else {
                    shopInsertLog.add(sqfwShopsBaseInfo);
                    shopsBaseInfoService.insert(sqfwShopsBaseInfo);
                }
            }
            int importNum = listener.getData().size();
            if (0 < importNum) {
                resStr = "成功导入数据 " + importNum + " 条";
                if (updateNum > 0) {
                    resStr = resStr + "，其中更新数据 " + updateNum + " 条";
                }
                log.info("商铺数据导入日志：{} ", resStr);
            } else {
                resStr = "无有效数据导入";
            }
        } catch (Exception e) {
            log.error("导入异常： {}", e.getMessage());
        } finally {
            listener.clear();
        }
        // 记录日志
        sysLogService.insertUpdateLog(SecurityUtil.getUserId(), "更新：" + JSONObject.toJSONString(shopUpdateLog)
                        + "新增：" + JSONObject.toJSONString(shopInsertLog), "shequ.sqfw_shops_base_info",
                "com.budwk.app.sqfw.services.communityService.SqfwShopInfoForAdminService.uploadShopInfo", "");
        return resStr;
    }

    /**
     * 导出商铺信息
     *
     * @param bean
     */
    public String exportShopInfo(SqfwShopInfoVO bean) {
        if (null == bean) {
            throw new AppException(ResultCode.PARAM_ERROR.getMsg());
        }
        List<SqfwShopInfoVO> sqfwShopInfoVOS = new ArrayList<SqfwShopInfoVO>();
        List<SqfwShopsBaseInfo> sqfwShopsBaseInfos = new ArrayList<SqfwShopsBaseInfo>();
        if (ObjectUtil.isEmpty(bean.getIds())) {
            // 构造查询条件
            Criteria criteria = buildQueryCond(bean);
            sqfwShopsBaseInfos = shopsBaseInfoService.query(criteria);
        } else {
            // 根据id查询
            Cnd cnd = Cnd.NEW();
            cnd.and("id", "IN", bean.getIds());
            sqfwShopsBaseInfos = shopsBaseInfoService.query(cnd);
        }
        String url = "";
        if (ObjectUtil.isNotEmpty(sqfwShopsBaseInfos)) {
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictInfoMaps(Arrays.asList(DictConstants.MAIN_BUSINESS_SCOPE));
            sqfwShopsBaseInfos.forEach(source -> {
                SqfwShopInfoVO target = new SqfwShopInfoVO();
                BeanUtil.copyProperties(source, target);
                // 主营业务转换
                target.setMainBusinessScopeName(StringUtils.isEmpty(dictCodesMap.get(target.getMainBusinessScope())) ?
                        target.getMainBusinessScope() : dictCodesMap.get(target.getMainBusinessScope()));
                // 业务类型转换
                String serviceType = target.getServiceType();
                if (StringUtils.isNotEmpty(serviceType)) {
                    List<String> serviceTypes = Arrays.asList(serviceType.split(","));
                    StringBuffer sb = new StringBuffer();
                    serviceTypes.forEach(service -> {
                        sb.append(SupportBusinessTypeEnum.getNameByCode(service)).append(",");
                    });
                    serviceType = sb.substring(0, sb.length() - 1);
                }
                target.setServiceTypeName(StringUtils.isNotEmpty(serviceType) ? serviceType : target.getServiceType());
                String shopStatus = target.getShopStatus();
                if (StringUtils.isNotEmpty(shopStatus)) {
                    if ("1".equals(shopStatus) || "2".equals(shopStatus)) {
                        target.setShopStatus("正常营业");
                    } else if ("3".equals(shopStatus)) {
                        target.setShopStatus("已停业");
                    }
                }
                sqfwShopInfoVOS.add(target);
            });
            long startTime = System.currentTimeMillis();
            try {
                url = createExcel(sqfwShopInfoVOS);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        // 记录日志
        List<String> ids = sqfwShopsBaseInfos.stream().map(SqfwShopsBaseInfo::getId).collect(Collectors.toList());
        saveLog("导出商铺数据", "导出商铺数据", JSONUtil.toJsonStr(ids));
        return url;
    }

    private String createExcel(List<SqfwShopInfoVO> sqfwShopInfoVOS) {
        if (sqfwShopInfoVOS.size() == 0) {
            throw new ServiceException("暂无数据");
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        int i = 0;
        for (SqfwShopInfoVO sqfwShopInfoVO : sqfwShopInfoVOS) {
            Map<String, Object> map = new HashMap<>();
            i++;
            map.put("num", i);
            map.put("placeName", sqfwShopInfoVO.getPlaceName());
            map.put("mainBusinessScopeName", sqfwShopInfoVO.getMainBusinessScopeName());
            map.put("address", sqfwShopInfoVO.getAddress());
            map.put("businessLicenseName", sqfwShopInfoVO.getBusinessLicenseName());
            if (StringUtils.isNotEmpty(sqfwShopInfoVO.getBusinessLicenseImage())) {
                List<byte[]> imgBytes = CommonFormOfficeUtils.addPictureToByteList(sqfwShopInfoVO.getBusinessLicenseImage(), 1);
                map.put("businessLicenseImage", imgBytes);
            } else {
                map.put("businessLicenseImage", null);
            }
            map.put("socialCreditCode", sqfwShopInfoVO.getSocialCreditCode());
            map.put("operator", sqfwShopInfoVO.getOperator());
            map.put("operatorTelephone", sqfwShopInfoVO.getOperatorTelephone());
            map.put("placeArea", sqfwShopInfoVO.getPlaceArea());
            map.put("type", sqfwShopInfoVO.getType());
            map.put("shopStatus", sqfwShopInfoVO.getShopStatus());
            map.put("serviceTypeName", sqfwShopInfoVO.getServiceTypeName());
            map.put("area", sqfwShopInfoVO.getProvince() + sqfwShopInfoVO.getCity() + sqfwShopInfoVO.getDistrict() + sqfwShopInfoVO.getCounty() + sqfwShopInfoVO.getCommunity());
            map.put("updateDate", DateUtil.format(sqfwShopInfoVO.getUpdateDate(), "yyyy-MM-dd hh:mm:ss"));
            mapList.add(map);
        }
        String templatePath = CommonFormOfficeUtils.getTemplatePathByOS("/shopInfo/shopInfo.xlsx");
        ExcelFileCreateParamBO excelFileCreateParam = new ExcelFileCreateParamBO();
        excelFileCreateParam.setTemplatePath(templatePath);
        excelFileCreateParam.setSheetParam(new HashMap<>());
        excelFileCreateParam.setDataList(mapList);
        excelFileCreateParam.setClazz(SqfwShopInfoDownloadBO.class);
        excelFileCreateParam.setFileName("商铺信息");
        excelFileCreateParam.setReturnWebUrlFlag(true);
        return CommonFormOfficeUtils.createExcelAndUpload(excelFileCreateParam);
    }

    /**
     * 删除商铺数据
     *
     * @param ids
     * @return
     */
    @Aop(TransAop.READ_COMMITTED)
    public int batchDelete(List<String> ids) {
        int num = 0;
        List<SqfwShopsBaseInfo> sqfwShopsBaseInfos = shopsBaseInfoService.query(Cnd.where(SqfwShopsBaseInfo::getId, "IN", ids));
        if (sqfwShopsBaseInfos == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        try {
            CompletableFuture.runAsync(() -> {
                batchDeleteShopData(sqfwShopsBaseInfos, userId);
            }, executorService);
        } catch (Exception ex) {
            log.error("删除商铺数据异常：{}", ids);
        } finally {
            executorService.shutdown();
        }
        return sqfwShopsBaseInfos.size();
    }

    /**
     * 批量删除
     *
     * @param sqfwShopsBaseInfos
     */
    @Aop(TransAop.READ_COMMITTED)
    private void batchDeleteShopData(List<SqfwShopsBaseInfo> sqfwShopsBaseInfos, String userId) {
        //1 记录日志
        List<String> ids = sqfwShopsBaseInfos.stream().map(SqfwShopsBaseInfo::getId).collect(Collectors.toList());
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(ids), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.communityService.SqfwShopInfoForAdminService.batchDeleteShopData",
                "com.budwk.app.sqfw.controllers.admin.SqfwShopInfoForAdminController.batchDelete");
        // 2 删除数据
        shopsBaseInfoService.delete(ids);
    }

    /**
     * 获取主营业务枚举
     *
     * @return
     */
    public List<Sys_dict> getMainBusinessInfo() {
        String mainBussinessScope = DictConstants.MAIN_BUSINESS_SCOPE;
        List<Sys_dict> sysDictsRes = new ArrayList<Sys_dict>();
        List<Sys_dict> sysDicts = sysDictService.getSubListByCode(mainBussinessScope);
        sysDicts.forEach(sysDict -> {
            Sys_dict sysDict1 = new Sys_dict();
            sysDict1.setCode(sysDict.getCode());
            sysDict1.setName(sysDict.getName());
            sysDictsRes.add(sysDict1);
        });
        return sysDictsRes;
    }

    /**
     * 根据商铺id查巡查记录
     *
     * @param bean
     * @return
     */
    public Pagination pageByShopId(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getShopsBaseInfoId())) {
            return new Pagination();
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildShopQueryCond(bean);
        log.info("pageByShopId-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        // 查询流程pdf
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictInfoMaps(Arrays.asList(DictConstants.MAIN_BUSINESS_SCOPE,
                    DictConstants.SHAWEN_BUSSINESS_SCOPE));
            // 字典列表查询
            Map<String, String> dictCodesMapSocial = CommonCheckUtils.getDictSubInfoMaps(Arrays.asList(
                    "place_types_entertainment_venues_daying_road", "place_types_key_dining_venues_daying_road",
                    "place_types_health_service_daying_road", "place_types_health_care_daying_road",
                    "place_types_education_training_daying_road", "place_types_fraud_risks_daying_road",
                    "place_types_large_comprehensive_daying_road", "place_types_key_service_other_daying_road",
                    "dining_venues_wedding_square_daying_road", "dining_venues_large_scale_restaurant_daying_road",
                    "dining_venues_night_market_daying_road", "dining_venues_other_daying_road",
                    "health_service_hospital_daying_road", "health_service_clinic_daying_road",
                    "health_service_plastic_surgery_daying_road", "health_service_other_daying_road",
                    "health_care_beadhouse_daying_road", "health_care_sanatorium_daying_road",
                    "health_care_rhabilitation_center_daying_road", "health_care_other_daying_road",
                    "education_training_university_daying_road", "education_training_middle_school_daying_road",
                    "education_training_primary_school_daying_road", "education_training_kindergarten_daying_road",
                    "education_training_tutoring_institutions_daying_road", "education_training_training_center_daying_road",
                    "education_training_childcare_institutions_daying_road", "education_training_other_daying_road",
                    "fraud_risks_bank_daying_road", "fraud_risks_eelephone_card_daying_road",
                    "fraud_risks_professional_sales_daying_road", "fraud_risks_other_daying_road",
                    "large_comprehensive_commercial_complex_daying_road", "large_comprehensive_large_shopping_mall_daying_road",
                    "large_comprehensive_farm_product_market_daying_road", "large_comprehensive_gathering_places_daying_road",
                    "large_comprehensive_religious_facilities_daying_road", "large_comprehensive_medium_square_daying_road",
                    "large_comprehensive_other_daying_road", "key_other_foot_massage_shop_daying_road",
                    "key_other_massage_parlour_daying_road", "key_other_beauty_salon_daying_road",
                    "key_other_health_club_daying_road", "key_other_gym_daying_road", "key_other_bath_centre_daying_road",
                    "key_other_hotel_daying_road", "key_other_bg_hotel_daying_road", "key_other_hostel_daying_road",
                    "key_other_other_daying_road", "entertainment_venues_bar_daying_road", "entertainment_venues_ktv_daying_road",
                    "entertainment_venues_nightclub_daying_road", "entertainment_venues_internet_bar_daying_road",
                    "entertainment_venues_chess_card_club_daying_road", "entertainment_venues_script_kill_daying_road"
                    , "entertainment_venues_cinema_daying_road", "entertainment_venues_other_daying_road", "small_business_premises_place_types"));
            sqfwCustomForAdminCommonVOList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                ShopInfoRecordMainKeyDTO safetyDTO = JSONObject.parseObject(target.getParamData(), ShopInfoRecordMainKeyDTO.class);
                if (ObjectUtil.isNotEmpty(safetyDTO)) {
                    String mainBusinessScope = "";
                    if (ObjectUtil.isNotEmpty(safetyDTO.getSmallBusinessEstablishment())) {
                        mainBusinessScope = safetyDTO.getSmallBusinessEstablishment().getMainBusinessScope();
                    } else if (StringUtils.isNotEmpty(safetyDTO.getMainBusinessScope())) {
                        mainBusinessScope = safetyDTO.getMainBusinessScope();
                    }
                    if (StringUtils.isNotEmpty(mainBusinessScope)) {
                        String[] mainBusinessScopes = mainBusinessScope.split(",");
                        StringBuffer sb = new StringBuffer();
                        for (String mainBusiness : mainBusinessScopes) {
                            String finalMainBusiness = dictCodesMap.get(mainBusiness);
                            if (StringUtils.isNotEmpty(finalMainBusiness)) {
                                sb.append(finalMainBusiness).append(",");
                            } else {
                                String finalMainBusinessSocial = dictCodesMapSocial.get(mainBusiness);
                                if (StringUtils.isNotEmpty(finalMainBusinessSocial)) {
                                    sb.append(finalMainBusinessSocial).append(",");
                                } else {
                                    sb.append(mainBusiness).append(",");
                                }
                            }
                        }
                        target.setMainBusinessScopeName(sb.substring(0, sb.length() - 1));
                    }
                    // 存在隐患
                    boolean isHiddenDanger1 = safetyDTO.getWhetherThereIsAnyHiddenDanger();
                    boolean isHiddenDanger2 = safetyDTO.getIsExistDanger();
                    boolean isHiddenDanger3 = safetyDTO.getInCrimeAndEvil();
                    if (StringUtils.isEmpty(target.getIssueStatus())) {
                        if (isHiddenDanger1 || isHiddenDanger2 || isHiddenDanger3) {
                            target.setIssueStatus("1");
                        } else {
                            target.setIssueStatus("0");
                        }
                    }
                }
                if (StringUtils.isEmpty(target.getIssueStatus())) {

                }
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("pageByShopId-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    private Criteria buildShopQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        // 组装查询条件
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);
        // 商铺id
        criSql.andEquals(Sqfw_formSummary_new::getShopsBaseInfoId, bean.getShopsBaseInfoId());
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonForAdminConstants.ZHISHU.equals(bean.getProvince())) {
            criSql.andLike(Sqfw_formSummary_new::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonForAdminConstants.ZHISHU.equals(bean.getCity())) {
            criSql.andLike(Sqfw_formSummary_new::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonForAdminConstants.ZHISHU.equals(bean.getDistrict())) {
            criSql.andLike(Sqfw_formSummary_new::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonForAdminConstants.ZHISHU.equals(bean.getCounty())) {
            criSql.andLike(Sqfw_formSummary_new::getCounty, bean.getCounty());
        }
        // 社区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonForAdminConstants.ZHISHU.equals(bean.getCounty())) {
            criSql.andLike(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup operator = Cnd.exps("param_data->>'operator'", "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup placeName = Cnd.exps("param_data->>'placeName'", "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup createName = Cnd.exps(Sqfw_formSummary_new::getCreateUserName, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup county = Cnd.exps(Sqfw_formSummary_new::getCounty, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup district = Cnd.exps(Sqfw_formSummary_new::getDistrict, "like", "%" + bean.getQueryAll() + "%");
            SqlExpressionGroup community = Cnd.exps(Sqfw_formSummary_new::getCommunity, "like", "%" + bean.getQueryAll() + "%");
            criSql.and(placeName.or(createName).or(county).or(district).or(community).or(operator));
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween("fill_date",
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 检查人员
        if (StringUtils.isNotEmpty(bean.getCreateUserName())) {
            criSql.andLike(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        // 负责人
        if (StringUtils.isNotEmpty(bean.getOperator())) {
            criSql.andLike("param_data->>'operator'", bean.getOperator());
        }
        // 是否隐患
        if (StringUtils.isNotBlank(bean.getIssueStatus())) {
            if ("1".equals(bean.getIssueStatus())) {
                criSql.and(new Static("(param_data->>'whetherThereIsAnyHiddenDanger' = 'true' " +
                        "OR param_data->>'InCrimeAndEvil' = 'true' OR param_data->>'isExistDanger' = 'true' " +
                        "OR issue_status != '0')"));
            } else if ("0".equals(bean.getIssueStatus())) {
                criSql.and(new Static("(param_data->>'whetherThereIsAnyHiddenDanger' = 'false' " +
                        "OR param_data->>'InCrimeAndEvil' = 'false' OR param_data->>'isExistDanger' = 'false' " +
                        "OR issue_status = '0')"));
            }
        }
        return cri;
    }

    /**
     * 登记日志
     *
     * @param tag
     * @param msg
     * @param params
     */
    private void saveLog(String tag, String msg, String params) {
        try {
            Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
            Sys_log sysLog = new Sys_log();
            sysLog.setId(R.UU32())
                    .setUserId(sysUser.getId())
                    .setUsername(sysUser.getUsername())
                    .setLoginname(sysUser.getLoginname())
                    .setTag(tag)
                    .setMsg(msg)
                    .setMethod("")
                    .setUrl("")
                    .setIp(sysUser.getLoginIp())
                    .setParams(params)
                    .setType(LogType.ACTION.getValue())
                    .setResult(JSONObject.toJSONString(Result.success("记录成功")))
                    .setOs("Unknown")
                    .setCreatedBy(sysUser.getId())
                    .setCreatedAt(System.currentTimeMillis())
                    .setDelFlag(false);
            sysLogService.save(sysLog);
        } catch (Exception ex) {
            log.error("登记日志失败：{}", ex.getMessage());
        }
    }
}
